package com.ece.items;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;

import com.ece.beans.items.DVD;
import com.ece.beans.items.Item;
import com.ece.beans.items.Livre;
import com.ece.persistence.PersistenceUtil;

@Stateless
public class ItemBusinessController implements ItemBusinessControllerRemote {

	public List<Item> getAllLivres() {
		List<Item> livres = new ArrayList<Item>();

		PersistenceUtil.init();
		EntityManager em = PersistenceUtil.getEM();
		try {
			PersistenceUtil.beginTransaction();
			livres = em.createQuery("from " + Livre.class.getName()).getResultList();
			PersistenceUtil.commitTransaction();
		}
		finally { PersistenceUtil.closeEM(); }

		return livres;
	}

	public List<Item> getAllDvd() {
		List<Item> dvds = new ArrayList<Item>();

		PersistenceUtil.init();
		EntityManager em = PersistenceUtil.getEM();
		try {
			PersistenceUtil.beginTransaction();
			dvds = em.createQuery("from " + DVD.class.getName()).getResultList();
			PersistenceUtil.commitTransaction();
		}
		finally { PersistenceUtil.closeEM(); }

		return dvds;
	}

	public Livre getLivre(String ref) {
		Livre livre;

		PersistenceUtil.init();
		EntityManager em = PersistenceUtil.getEM();
		try {
			PersistenceUtil.beginTransaction();
			livre = (Livre)em.createQuery("from " + Livre.class.getName() + " where ITEM_REF='" + ref + "'").getSingleResult();
			PersistenceUtil.commitTransaction();
		}
		finally { PersistenceUtil.closeEM(); }

		return livre;
	}

	public DVD getDvd(String ref) {
		DVD dvd;

		PersistenceUtil.init();
		EntityManager em = PersistenceUtil.getEM();
		try {
			PersistenceUtil.beginTransaction();
			dvd = (DVD)em.createQuery("from " + DVD.class.getName() + " where ITEM_REF='" + ref + "'").getSingleResult();
			PersistenceUtil.commitTransaction();
		}
		finally { PersistenceUtil.closeEM(); }

		return dvd;
	}

}
